import { ProTable } from '@ant-design/pro-components';
import {
  Button,
  Popconfirm,
  message,
  Tag,
  Upload,
  Image,
  Table,
  Space,
  Breadcrumb,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { useRequest } from 'umi';
import type { UploadProps } from 'antd';
import { UploadOutlined, FileSearchOutlined } from '@ant-design/icons';
import React, { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import ImportExcel from '@/pages/LabManage/component/ImportExcel';

import {
  ModalForm,
  ProForm,
  ProFormSelect,
  ProFormText,
  ProFormDatePicker,
} from '@ant-design/pro-components';
import { useBoolean } from 'ahooks';

export default () => {
  const formRef = useRef<ProFormInstance>();
  const editformRef = useRef<ProFormInstance>();
  const [selectRow, { toggle }] = useBoolean(false);
  const props: UploadProps = {
    name: 'file',
    action: 'http://10.1.40.84:9993/common/uploadFile',
    headers: {
      Authorization: localStorage.getItem('token') || '',
    },
    maxCount: 1,
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        formRef.current?.setFieldsValue({ annexPath: info.file.response.data });
        editformRef.current?.setFieldsValue({
          annexPath: info.file.response.data,
        });
        message.success(`${info.file.name} 上传成功！`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },
  };
  const updateStatus = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/common/updateStatus',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  //获取 领导调研列表
  const findAllResearch = useRequest((data = undefined) => {
    return {
      url: `http://10.1.40.84:9993/research/findAllResearch`,
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('token') || '',
      },
      data,
    };
  });
  //新增期刊
  const insertResearch = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/research/insertResearch`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //删除 领导调研
  const delResearch = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/research/delResearch`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );
  //编辑 领导调研
  const updateResearch = useRequest(
    (data = undefined) => {
      return {
        url: `http://10.1.40.84:9993/research/updateResearch`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      manual: true,
    },
  );

  const confirm = (e: any) => {
    delResearch.run({ id: e.id }).then(() => {
      findAllResearch.run();
      message.success('删除成功');
    });
  };
  const cancel = (e: any) => {
    message.error('已取消');
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'seq',
      align: "center",
      width: "10%",
      key: 'seq',
      // copyable: true,
      hideInSearch: true,
    },
    {
      title: '调研年份',
      colSize: 0.8,
      align: "center",
      width: "10%",
      dataIndex: 'year',
      key: 'year',
      valueType: 'dateYear',
      hideInTable: true,
    },
    {
      title: '调研年份',
      align: "center",
      width: "10%",
      dataIndex: 'year',
      key: 'year',
      sorter: {
        compare: (a, b) => a.year - b.year,
      },
      hideInSearch: true,
    },
    {
      title: '领导姓名',
      colSize: 0.8,
      align: "center",
      width: "10%",
      dataIndex: 'leaderName',
      key: 'leaderName',
      // copyable: true,
    },

    {
      title: '报告人职称/职务',
      colSize: 0.8,
      align: "center",
      width: "10%",
      dataIndex: 'reporterTechnicalGrade',
      key: 'reporterTechnicalGrade',
    },
    {
      title: '报告人单位',
      colSize: 0.8,
      align: "center",
      width: "10%",
      dataIndex: 'reporterWorkUnit',
      key: 'reporterWorkUnit',
    },
    {
      title: '报告人头衔',
      colSize: 0.8,
      align: "center",
      width: "10%",
      dataIndex: 'reporterTechnicalName',
      key: 'reporterTechnicalName',
    },

    {
      title: '调研时间',
      align: "center",
      width: "10%",
      dataIndex: 'researchTime',
      key: 'researchTime',
      hideInSearch: true,
    },
    // {
    //   title: '佐证材料状态',
    //   dataIndex: 'annexState',
    //   key: 'annexState',
    //   hideInSearch: true,
    // },
    {
      title: '报道',
      align: "center",
      width: "10%",
      dataIndex: 'reportLink',
      key: 'reportLink',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.reportLink !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              查看链接
            </a>
          );
        } else {
          return <span>暂无报道</span>;
        }
      },
    },
    {
      title: '材料',
      align: "center",
      width: "10%",
      dataIndex: 'annexPath',
      key: 'annexPath',
      hideInSearch: true,
      render: (text: any, record: any) => {
        if (record.annexPath !== null) {
          return (
            <a
              onClick={() => {
                window.open(text);
              }}
            >
              下载
            </a>
          );
        } else {
          return <span>暂无材料</span>;
        }
      },
    },
    {
      title: '操作',
      align: "center",
      width: "10%",
      key: 'option',
      valueType: 'option',
      render: (text: any, record: any) => {
        return(
          <div>
            <ModalForm
              layout={"horizontal"}
              title="查看"
              trigger={<a key="1">查看&nbsp;</a>}
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
              }}
              submitTimeout={2000}
              initialValues={record}
              key="1"
              grid={true}
            >
              <ProForm.Group >
                <ProFormText name="id" hidden />
                <ProFormText readonly={true} name="year" label="年份"  />
                <ProFormText
                  readonly={true}
                  name="leaderName"
                  label="领导姓名"
                />
                <ProFormText
                  readonly={true}
                  label="报告人职称/职务"
                  name={'reporterTechnicalGrade'}
                />

                <ProFormText
                  readonly={true}
                  label="报告人头衔"
                  name={'reporterTechnicalName'}
                />

                <ProFormText
                  readonly={true}
                  label="报告人单位"
                  name={'reporterWorkUnit'}
                />
                <ProFormDatePicker
                  readonly={true}
                  name="researchTime"
                  label="调研时间"
                />
                <ProFormDatePicker name="annexPath" hidden />
                <ProFormText
                  readonly={true}
                  name="researchContent"
                  label="调研内容"
                />
                <ProFormText
                  readonly={true}
                  name="reportLink"
                  label="报道链接"
                />
              </ProForm.Group>
            </ModalForm>

            <ModalForm
              title="编辑调研"
              trigger={<a key="2">编辑&nbsp;</a>}
              autoFocusFirstInput
              modalProps={{
                onCancel: () => console.log('run'),
              }}
              submitTimeout={2000}
              onFinish={async (values) => {
                updateResearch.run(values).then(() => {
                  message.info('编辑成功！');
                  findAllResearch.run();
                });
                return true;
              }}
              initialValues={record}
              key="1"
              formRef={editformRef}
              grid={true}
            >
              <ProForm.Group>
                <ProFormText name="id" hidden />
                <ProFormText name="year" label="年份" colProps={{ span: 6 }} />
                <ProFormText
                  name="leaderName"
                  label="领导姓名"
                  colProps={{ span: 6 }}
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormText
                  label="报告人职称/职务"
                  name={'reporterTechnicalGrade'}
                  colProps={{ span: 6 }}
                  rules={[{ required: true, message: '请输入报告人职称/职务' }]}
                />

                <ProFormText
                  label="报告人头衔"
                  name={'reporterTechnicalName'}
                  colProps={{ span: 6 }}
                />

                <ProFormText
                  label="报告人单位"
                  name={'reporterWorkUnit'}
                  colProps={{ span: 12 }}
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormDatePicker
                  colProps={{ span: 6 }}
                  name="researchTime"
                  label="调研时间"
                  rules={[{ required: true, message: '请选择' }]}
                />
                <ProFormDatePicker colProps={{ span: 6 }} name="annexPath" hidden />
                <ProFormText
                  colProps={{ span: 6 }}
                  name="researchContent"
                  label="调研内容"
                  rules={[{ required: true, message: '请输入' }]}
                />
                <ProFormText
                  colProps={{ span: 24 }}
                  name="reportLink"
                  label="报道链接"
                />
                <Upload {...props}>
                  <Button
                    icon={<UploadOutlined />}
                    type="link"
                    style={{ marginTop: 30 }}
                  >
                    上传材料（上传会议照片，以会议名称命名）
                  </Button>
                </Upload>
              </ProForm.Group>
            </ModalForm>

            <Popconfirm
              key={'3'}
              title="确定删除吗？"
              onConfirm={() => confirm(record)}
              onCancel={() => cancel}
              okText="确定"
              cancelText="取消"
            >
              <a href="#">删除</a>
            </Popconfirm>
          </div>
        )
      },
    },
  ];

  const Refresh = () => {
    findAllResearch.run();
  };

  return (
    <PageContainer
      header={{
        title: null,
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>合作交流</Breadcrumb.Item>
            <Breadcrumb.Item>领导调研</Breadcrumb.Item>
          </Breadcrumb>
        ),
        extra: [],
      }}
    >
      <ProTable
        columns={columns}
        dataSource={findAllResearch?.data}
        rowKey="id"
        pagination={{
          showQuickJumper: true,
        }}
        onSubmit={(e: any) => {
          findAllResearch.run(e);
        }}
        onReset={() => {
          findAllResearch.run();
        }}
        search={{ labelWidth: 'auto' ,collapsed:true, span:0.5}}
        loading={findAllResearch.loading}
        dateFormatter="string"
        headerTitle="调研列表"
        options={false}
        toolBarRender={() => [
          <ImportExcel
            tableName={'LEADER_RESEARCH'}
            Refresh={Refresh}
          />,
          <Button
            type="primary"
            onClick={() => {
              window.open(
                'http://10.1.40.84:9993/file/model/LEADER_RESEARCH_模板.xlsx ',
              );
            }}
          >
            下载模版
          </Button>,
          <ModalForm
            title="新增调研"
            trigger={
              <Button key="primary" type="primary">
                新增调研
              </Button>
            }
            autoFocusFirstInput
            modalProps={{
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            onFinish={async (values) => {
              console.log(values);
              insertResearch.run(values).then(() => {
                findAllResearch.run();
                message.info('添加成功！');
              });
              return true;
            }}
            key="1"
            formRef={formRef}
            grid={true}
          >
            <ProForm.Group>
              <ProFormDatePicker.Year
                colProps={{ span: 6 }}
                name="year"
                label="年份"
              />
              <ProFormText
                colProps={{ span: 6 }}
                name="leaderName"
                label="领导姓名"
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                label="报告人职称/职务"
                name={'reporterTechnicalGrade'}
                colProps={{ span: 6 }}
                rules={[{ required: true, message: '请输入报告人职称/职务' }]}
              />

              <ProFormText
                label="报告人头衔"
                name={'reporterTechnicalName'}
                colProps={{ span: 6 }}
              />

              <ProFormText
                label="报告人单位"
                name={'reporterWorkUnit'}
                colProps={{ span: 12 }}
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormDatePicker
                colProps={{ span: 6 }}
                name="researchTime"
                label="调研时间"
                rules={[{ required: true, message: '请选择' }]}
              />
              <ProFormDatePicker
                colProps={{ span: 6 }}
                name="annexPath"
                hidden
              />
              <ProFormText
                colProps={{ span: 6 }}
                name="researchContent"
                label="调研内容"
                rules={[{ required: true, message: '请输入' }]}
              />
              <ProFormText
                colProps={{ span: 24 }}
                name="reportLink"
                label="报道链接"
              />
              <Upload {...props}>
                <Button
                  icon={<UploadOutlined />}
                  type="link"
                  style={{ marginTop: 30 }}
                >
                  上传材料（上传会议照片，以会议名称命名）
                </Button>
              </Upload>
            </ProForm.Group>
          </ModalForm>,
          // <ImportExcel
          //   key="1"
          //   tableName={'LEADER_RESEARCH'}
          //   Refresh={Refresh}
          // />,
          // <Button
          //   key="2"
          //   type="primary"
          //   onClick={() => {
          //     window.open(
          //       'http://10.1.40.84:9993/file/model/LEADER_RESEARCH_模板.xlsx ',
          //     );
          //   }}
          // >
          //   下载模版
          // </Button>,
        ]}
        rowSelection={
          selectRow
            ? {
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
              }
            : false
        }
        tableAlertOptionRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={16}>
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'LEADER_RESEARCH',
                    ids: selectedRowKeys,
                    status: 2, //审核通过
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllResearch.run();
                  });
              }}
            >
              审核通过
            </a>
            <a
              onClick={() => {
                updateStatus
                  .run({
                    tableName: 'LEADER_RESEARCH',
                    ids: selectedRowKeys,
                    status: 3, //拒绝
                  })
                  .then(() => {
                    message.success('操作成功');
                    onCleanSelected();
                    toggle();
                    findAllResearch.run();
                  });
              }}
            >
              拒绝
            </a>
          </Space>
        )}
      />
    </PageContainer>
  );
};
